﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Security
    {
        private readonly static object _sync_lock = new object();
        public void Show()
        {
            var t1=TestAsync("One");
            var t2=TestAsync("Two");

            Task.WaitAll(t1, t2);
            Console.ReadKey();
        }

        private static async Task TestAsync(string name)
        {
          await  Task.Factory.StartNew(() =>
            {
                var r = new Random();
                for (var i = 0; i < 10000; i++)
                {
                    var str = $"{name}:{Guid.NewGuid()}";
                    SecurityModel.SetMyName(str);
                    Task.Delay(r.Next(30, 1000)).Wait();
                    var result = SecurityModel.GetName();

                    var flag = result == str;
                    lock (_sync_lock)
                    {
                        Console.BackgroundColor = flag ? ConsoleColor.Green : ConsoleColor.Red;
                        Console.WriteLine($"[{flag}]:{result}");
                    }
                }
            });
        }
    }

    public static class SecurityModel
    {
        static AsyncLocal<string> myName = new AsyncLocal<string>();

        public static void SetMyName(string name)
        {
            myName.Value = name;
        }

        public static string GetName()
        {
            return myName.Value;
        }
    }
}
